import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Tag, Space, message, Avatar, Card, Row, Col } from 'antd';
import { SearchOutlined, StarOutlined, StarFilled, UserOutlined } from '@ant-design/icons';

const ManagerList = () => {
  const [managers, setManagers] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');

  // 模拟基金经理数据
  const mockManagers = [
    {
      id: 1,
      name: '张坤',
      company: '易方达基金',
      experience: 12,
      fundCount: 8,
      totalAssets: 1200,
      avgReturn: 18.5,
      tags: ['价值投资', '消费行业', '长期持有'],
      rating: 5,
      description: '易方达基金副总经理，专注于消费行业投资'
    },
    {
      id: 2,
      name: '刘彦春',
      company: '景顺长城基金',
      experience: 15,
      fundCount: 6,
      totalAssets: 980,
      avgReturn: 16.8,
      tags: ['成长投资', '医药行业', '科技股'],
      rating: 5,
      description: '景顺长城基金副总经理，擅长成长股投资'
    },
    {
      id: 3,
      name: '葛兰',
      company: '中欧基金',
      experience: 8,
      fundCount: 5,
      totalAssets: 750,
      avgReturn: 22.3,
      tags: ['医药行业', '创新药', '高成长'],
      rating: 4,
      description: '中欧基金基金经理，专注于医药行业投资'
    },
    {
      id: 4,
      name: '谢治宇',
      company: '兴证全球基金',
      experience: 10,
      fundCount: 7,
      totalAssets: 850,
      avgReturn: 15.2,
      tags: ['均衡配置', '价值成长', '稳健'],
      rating: 4,
      description: '兴证全球基金副总经理，投资风格稳健'
    },
    {
      id: 5,
      name: '萧楠',
      company: '易方达基金',
      experience: 11,
      fundCount: 4,
      totalAssets: 680,
      avgReturn: 14.8,
      tags: ['消费行业', '白酒', '价值投资'],
      rating: 4,
      description: '易方达基金基金经理，专注于消费行业'
    },
    {
      id: 6,
      name: '王宗合',
      company: '鹏华基金',
      experience: 13,
      fundCount: 9,
      totalAssets: 920,
      avgReturn: 13.5,
      tags: ['周期股', '制造业', '主题投资'],
      rating: 4,
      description: '鹏华基金副总经理，擅长周期股投资'
    },
    {
      id: 7,
      name: '朱少醒',
      company: '富国基金',
      experience: 16,
      fundCount: 3,
      totalAssets: 450,
      avgReturn: 19.2,
      tags: ['长期投资', '价值成长', '精选个股'],
      rating: 5,
      description: '富国基金副总经理，投资经验丰富'
    },
    {
      id: 8,
      name: '董承非',
      company: '兴证全球基金',
      experience: 14,
      fundCount: 6,
      totalAssets: 780,
      avgReturn: 12.8,
      tags: ['价值投资', '防御性', '低估值'],
      rating: 4,
      description: '兴证全球基金副总经理，投资风格保守'
    }
  ];

  useEffect(() => {
    setManagers(mockManagers);
    // 读取本地关注
    const stored = localStorage.getItem('managerFavorites');
    if (stored) setFavorites(JSON.parse(stored));
  }, []);

  const columns = [
    {
      title: '基金经理',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar icon={<UserOutlined />} style={{ marginRight: '8px' }} />
          <div>
            <div style={{ fontWeight: 'bold' }}>{name}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>{record.company}</div>
          </div>
        </div>
      ),
    },
    {
      title: '从业年限',
      dataIndex: 'experience',
      key: 'experience',
      width: 100,
      render: (experience) => <span style={{ fontWeight: 'bold', color: '#1890ff' }}>{experience}年</span>,
    },
    {
      title: '管理基金',
      dataIndex: 'fundCount',
      key: 'fundCount',
      width: 100,
      render: (count) => <span style={{ fontWeight: 'bold', color: '#52c41a' }}>{count}只</span>,
    },
    {
      title: '管理规模(亿)',
      dataIndex: 'totalAssets',
      key: 'totalAssets',
      width: 120,
      render: (assets) => <span style={{ fontWeight: 'bold', color: '#faad14' }}>{assets}</span>,
    },
    {
      title: '平均收益(%)',
      dataIndex: 'avgReturn',
      key: 'avgReturn',
      width: 120,
      render: (return_) => (
        <span style={{ fontWeight: 'bold', color: return_ > 0 ? '#52c41a' : '#f5222d' }}>
          {return_ > 0 ? '+' : ''}{return_}%
        </span>
      ),
    },
    {
      title: '投资风格',
      dataIndex: 'tags',
      key: 'tags',
      width: 200,
      render: (tags) => (
        <>
          {tags.map(tag => (
            <Tag color="blue" key={tag} style={{ marginBottom: '4px' }}>
              {tag}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '评级',
      dataIndex: 'rating',
      key: 'rating',
      width: 100,
      render: (rating) => (
        <div>
          {[...Array(5)].map((_, index) => (
            <span key={index} style={{ color: index < rating ? '#faad14' : '#d9d9d9' }}>
              ★
            </span>
          ))}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => {
        const isFavorited = favorites.some(fav => fav.id === record.id);
        return (
          <Button 
            type="link" 
            icon={isFavorited ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
            onClick={() => handleToggleFavorite(record)}
          >
            {isFavorited ? '已关注' : '关注'}
          </Button>
        );
      },
    },
  ];

  const handleToggleFavorite = (manager) => {
    const isFavorited = favorites.some(fav => fav.id === manager.id);
    let newFavorites;
    if (isFavorited) {
      newFavorites = favorites.filter(fav => fav.id !== manager.id);
      message.success(`已取消关注 ${manager.name}`);
    } else {
      newFavorites = [...favorites, manager];
      message.success(`已关注 ${manager.name}`);
    }
    setFavorites(newFavorites);
    localStorage.setItem('managerFavorites', JSON.stringify(newFavorites));
  };

  const handleRemoveFavorite = (managerId) => {
    const newFavorites = favorites.filter(fav => fav.id !== managerId);
    setFavorites(newFavorites);
    localStorage.setItem('managerFavorites', JSON.stringify(newFavorites));
    message.success('已从关注列表移除');
  };

  const handleSearch = (value) => {
    setSearchText(value);
  };

  const filteredData = managers.filter(manager => 
    manager.name.includes(searchText) || 
    manager.company.includes(searchText) ||
    manager.tags.some(tag => tag.includes(searchText))
  );

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>基金经理管理</h2>
        <Input.Search
          placeholder="输入经理姓名/公司/标签"
          style={{ width: 400 }}
          onSearch={handleSearch}
          onChange={(e) => setSearchText(e.target.value)}
        />
      </div>

      <Row gutter={16}>
        <Col span={18}>
          <Table 
            dataSource={filteredData} 
            columns={columns} 
            rowKey="id"
            loading={loading}
            pagination={{
              total: filteredData.length,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            }}
          />
        </Col>
        <Col span={6}>
          <Card title="关注列表" style={{ position: 'sticky', top: '24px' }}>
            {favorites.length === 0 ? (
              <div style={{ textAlign: 'center', color: '#999', padding: '20px 0' }}>
                暂无关注的基金经理
              </div>
            ) : (
              <div>
                {favorites.map(manager => (
                  <div 
                    key={manager.id} 
                    style={{ 
                      padding: '12px', 
                      border: '1px solid #f0f0f0', 
                      borderRadius: '6px', 
                      marginBottom: '8px',
                      background: '#fafafa'
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div>
                        <div style={{ fontWeight: 'bold', fontSize: '14px' }}>{manager.name}</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>{manager.company}</div>
                        <div style={{ fontSize: '12px', color: '#1890ff' }}>平均收益: {manager.avgReturn}%</div>
                      </div>
                      <Button 
                        type="text" 
                        size="small" 
                        danger
                        onClick={() => handleRemoveFavorite(manager.id)}
                      >
                        移除
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ManagerList; 